import { Router } from 'express';
import {
  ConversationService,
  MessageService,
} from '../services/conversation.service.js';
import { CharacterService } from '../services/character.service.js';
import { AIService } from '../services/ai.service.js';

const router = Router();

// 创建新对话
router.post('/', async (req, res) => {
  try {
    const { characterId, title } = req.body;

    if (!characterId) {
      return res.status(400).json({ error: '请提供角色ID' });
    }

    // 验证角色是否存在
    const character = await CharacterService.findById(characterId);
    if (!character) {
      return res.status(404).json({ error: '角色不存在' });
    }

    const conversation = await ConversationService.create(characterId, title);
    res.json({ success: true, data: conversation });
  } catch (error) {
    console.error('创建对话失败:', error);
    res.status(500).json({ error: '创建对话失败' });
  }
});

// 获取角色的所有对话
router.get('/character/:characterId', async (req, res) => {
  try {
    const { characterId } = req.params;
    const conversations =
      await ConversationService.findByCharacterId(characterId);
    res.json({ success: true, data: conversations });
  } catch (error) {
    console.error('获取对话列表失败:', error);
    res.status(500).json({ error: '获取对话列表失败' });
  }
});

// 获取对话详情和消息
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;

    const conversation = await ConversationService.findById(id);
    if (!conversation) {
      return res.status(404).json({ error: '对话不存在' });
    }

    const messages = await MessageService.findByConversationId(id);

    res.json({
      success: true,
      data: {
        conversation,
        messages,
      },
    });
  } catch (error) {
    console.error('获取对话详情失败:', error);
    res.status(500).json({ error: '获取对话详情失败' });
  }
});

// 发送消息
router.post('/:id/messages', async (req, res) => {
  try {
    const { id } = req.params;
    const { content } = req.body;

    if (!content) {
      return res.status(400).json({ error: '请提供消息内容' });
    }

    // 验证对话是否存在
    const conversation = await ConversationService.findById(id);
    if (!conversation) {
      return res.status(404).json({ error: '对话不存在' });
    }

    // 获取角色信息
    const character = await CharacterService.findById(conversation.characterId);
    if (!character) {
      return res.status(404).json({ error: '角色不存在' });
    }

    // 保存用户消息
    const userMessage = await MessageService.create(id, 'user', content);

    // 获取历史消息
    const historyMessages = await MessageService.findByConversationId(id);

    // 生成AI回复
    const aiResponse = await AIService.chat(
      character,
      historyMessages,
      content
    );

    // 保存AI回复
    const assistantMessage = await MessageService.create(
      id,
      'assistant',
      aiResponse
    );

    res.json({
      success: true,
      data: {
        userMessage,
        assistantMessage,
      },
    });
  } catch (error) {
    console.error('发送消息失败:', error);
    res.status(500).json({ error: error.message || '发送消息失败' });
  }
});

// 删除对话
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const success = await ConversationService.delete(id);

    if (!success) {
      return res.status(404).json({ error: '对话不存在' });
    }

    res.json({ success: true, message: '对话删除成功' });
  } catch (error) {
    console.error('删除对话失败:', error);
    res.status(500).json({ error: '删除对话失败' });
  }
});

export default router;
